﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CPlatePrintSys.Infrastructure;
using Prism.Commands;
using Prism.Events;
using System.Windows.Input;
using Prism.Mvvm;
using Prism.Navigation.Regions;
using CPlatePrintSys.Application.Services;
using CPlatePrintSys.Domain.Models;
using System.Collections.ObjectModel;
using CPlatePrintSys.Win.Models;
using System.Windows;
using System.IO;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace CPlatePrintSys.Win.ViewModels
{
    public class ShipNoConfigViewModel : BindableBase
    {

        private readonly IEventAggregator _eventAggregator;
        private readonly IRegionManager _regionManager;
        private readonly IShipConfigService _service;


        public ObservableCollection<MotherShip> MotherShips { get; } = new ObservableCollection<MotherShip>();
        public MotherShip SelectedMotherShip { get; set; }
        public string NewMotherShipNo { get; set; }
        public string NewStreamShipNo { get; set; }
        public MotherShip SelectedMotherForStream { get; set; }

        public ObservableCollection<ShipConfigDto> ShipConfigList { get; } = new ObservableCollection<ShipConfigDto>();

        public DelegateCommand MotherShipManageCommand { get; }
        public DelegateCommand<MotherShip> DeleteMotherShipCommand { get; }
        public DelegateCommand AddStreamShipCommand { get; }
        public DelegateCommand<ShipConfigDto> DeleteStreamShipCommand { get; }
        public DelegateCommand<ShipConfigDto> EditStreamShipCommand { get; }
        public DelegateCommand ImportCommand { get; }
        public DelegateCommand ExportCommand { get; }


        private string _subTitle = string.Empty;
        public string SubTitle
        {
            get { return _subTitle; }
            set { SetProperty(ref _subTitle, value); }
        }

        public ICommand BackToHomeCommand { get; }

        public ShipNoConfigViewModel(IRegionManager regionManager, IEventAggregator eventAggregator, IShipConfigService service)
        {
            _regionManager = regionManager;
            _eventAggregator = eventAggregator;
            _service = service;

            _subTitle = "船号配置";

            BackToHomeCommand = new DelegateCommand(BackToHome);
            MotherShipManageCommand = new DelegateCommand(ShowMotherShipManageDialog);
            DeleteMotherShipCommand = new DelegateCommand<MotherShip>(async m => await DeleteMotherShip(m));
            AddStreamShipCommand = new DelegateCommand(ShowAddStreamShipDialog);
            DeleteStreamShipCommand = new DelegateCommand<ShipConfigDto>(async dto => await DeleteStreamShip(dto));
            EditStreamShipCommand = new DelegateCommand<ShipConfigDto>(ShowEditStreamShipDialog);
            ImportCommand = new DelegateCommand(ImportFromExcel);
            ExportCommand = new DelegateCommand(ExportToExcel);
            LoadData();
        }

        private void BackToHome()
        {
            _regionManager.RequestNavigate(ConstStrings.UI_Region_Secondary_Content, "HomeView");
        }

        private async void LoadData()
        {
            MotherShips.Clear();
            ShipConfigList.Clear();
            var list = await _service.GetAllMotherShipsAsync();
            foreach (var m in list)
                MotherShips.Add(m);

            // 构建 ShipConfigList
            foreach (var m in MotherShips)
            {
                if (m.StreamShips != null)
                {
                    foreach (var s in m.StreamShips)
                    {
                        ShipConfigList.Add(new ShipConfigDto
                        {
                            StreamShipId = s.Id,
                            MotherShipNo = m.ShipNo,
                            StreamShipNo = s.ShipNo,
                            MotherShipId = m.Id
                        });
                    }
                }
            }
        }

        private async Task DeleteMotherShip(MotherShip m)
        {
            if (m == null) return;
            
            var result = MessageBox.Show(
                "删除后将影响已有的数据，是否继续？", 
                "确认删除", 
                MessageBoxButton.YesNo, 
                MessageBoxImage.Warning);
                
            if (result == MessageBoxResult.Yes)
            {
                await _service.DeleteMotherShipAsync(m.Id);
                LoadData();
            }
        }

        private async Task AddStreamShip()
        {
            if (SelectedMotherForStream == null || string.IsNullOrWhiteSpace(NewStreamShipNo)) return;
            await _service.AddStreamShipAsync(NewStreamShipNo.Trim().ToUpper(), SelectedMotherForStream.Id);
            LoadData();
            NewStreamShipNo = string.Empty;
            RaisePropertyChanged(nameof(NewStreamShipNo));
        }

        private async Task DeleteStreamShip(ShipConfigDto dto)
        {
            if (dto == null) return;
            
            var result = MessageBox.Show(
                "删除后将影响已有的数据，是否继续？", 
                "确认删除", 
                MessageBoxButton.YesNo, 
                MessageBoxImage.Warning);
                
            if (result == MessageBoxResult.Yes)
            {
                await _service.DeleteStreamShipAsync(dto.StreamShipId);
                LoadData();
            }
        }

        private void ShowMotherShipManageDialog()
        {
            var vm = new MotherShipManageViewModel(_service);
            var dlg = new Views.MotherShipManageView { DataContext = vm, Owner = System.Windows.Application.Current.MainWindow };
            dlg.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            dlg.ShowDialog();
            LoadData();
        }

        private void ShowAddMotherShipDialog()
        {
            var vm = new AddMotherShipViewModel(_service);
            var dlg = new Views.AddMotherShipView { DataContext = vm, Owner = System.Windows.Application.Current.MainWindow };
            dlg.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            if (dlg.ShowDialog() == true)
                LoadData();
        }

        private void ShowAddStreamShipDialog()
        {
            var vm = new AddStreamShipViewModel(_service, MotherShips.ToList());
            var dlg = new Views.AddStreamShipView { DataContext = vm, Owner = System.Windows.Application.Current.MainWindow };
            dlg.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            if (dlg.ShowDialog() == true)
                LoadData();
        }

        private void ShowEditStreamShipDialog(ShipConfigDto dto)
        {
            if (dto == null) return;
            var vm = new AddStreamShipViewModel(_service, MotherShips.ToList(), dto);
            var dlg = new Views.AddStreamShipView { DataContext = vm, Owner = System.Windows.Application.Current.MainWindow };
            dlg.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            if (dlg.ShowDialog() == true)
                LoadData();
        }

        private async void ImportFromExcel()
        {
            try
            {
                var openFileDialog = new Microsoft.Win32.OpenFileDialog
                {
                    Filter = "CSV文件 (*.csv)|*.csv|所有文件 (*.*)|*.*",
                    Title = "选择要导入的CSV文件"
                };

                if (openFileDialog.ShowDialog() == true)
                {
                    await ImportShipDataFromExcel(openFileDialog.FileName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("导入失败：{0}", ex.Message), "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void ExportToExcel()
        {
            try
            {
                var saveFileDialog = new Microsoft.Win32.SaveFileDialog
                {
                    Filter = "CSV文件 (*.csv)|*.csv",
                    Title = "保存CSV文件",
                    FileName = string.Format("船号配置_{0}.csv", DateTime.Now.ToString("yyyyMMdd_HHmmss"))
                };

                if (saveFileDialog.ShowDialog() == true)
                {
                    ExportShipDataToExcel(saveFileDialog.FileName);
                    MessageBox.Show("导出成功！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("导出失败：{0}", ex.Message), "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task ImportShipDataFromExcel(string filePath)
        {
            var importedCount = 0;
            var skippedCount = 0;
            var errorMessages = new List<string>();

            try
            {
                var lines = File.ReadAllLines(filePath, Encoding.UTF8);
                if (lines.Length < 2)
                {
                    throw new Exception("文件中没有数据行");
                }

                // 从第二行开始读取数据（第一行是标题）
                for (int rowIndex = 1; rowIndex < lines.Length; rowIndex++)
                {
                    try
                    {
                        var line = lines[rowIndex].Trim();
                        if (string.IsNullOrWhiteSpace(line))
                        {
                            skippedCount++;
                            continue;
                        }

                        // 解析CSV行（简单的逗号分隔）
                        var columns = ParseCsvLine(line);
                        if (columns.Count < 2)
                        {
                            errorMessages.Add(string.Format("第{0}行：数据列数不足", rowIndex + 1));
                            skippedCount++;
                            continue;
                        }

                        var motherShipNo = columns[0]?.Trim();
                        var streamShipNo = columns[1]?.Trim();

                        if (string.IsNullOrWhiteSpace(motherShipNo) || string.IsNullOrWhiteSpace(streamShipNo))
                        {
                            skippedCount++;
                            continue;
                        }

                        // 验证船号格式
                        if (!IsValidShipNo(motherShipNo) || !IsValidShipNo(streamShipNo))
                        {
                            errorMessages.Add(string.Format("第{0}行：船号格式不正确（应为大写字母+数字）", rowIndex + 1));
                            skippedCount++;
                            continue;
                        }

                        motherShipNo = motherShipNo.ToUpper();
                        streamShipNo = streamShipNo.ToUpper();

                        // 检查母船是否存在，如果不存在则创建
                        var motherShip = MotherShips.FirstOrDefault(m => m.ShipNo == motherShipNo);
                        if (motherShip == null)
                        {
                            await _service.AddMotherShipAsync(motherShipNo);
                            // 重新加载母船列表
                            var allMotherShips = await _service.GetAllMotherShipsAsync();
                            MotherShips.Clear();
                            foreach (var m in allMotherShips)
                                MotherShips.Add(m);
                            motherShip = MotherShips.FirstOrDefault(m => m.ShipNo == motherShipNo);
                        }

                        // 检查流用船是否已存在
                        var existingStreamShip = ShipConfigList.FirstOrDefault(s => s.StreamShipNo == streamShipNo);
                        if (existingStreamShip == null)
                        {
                            await _service.AddStreamShipAsync(streamShipNo, motherShip.Id);
                            importedCount++;
                        }
                        else
                        {
                            skippedCount++;
                        }
                    }
                    catch (Exception ex)
                    {
                        errorMessages.Add(string.Format("第{0}行：{1}", rowIndex + 1, ex.Message));
                        skippedCount++;
                    }
                }

                // 重新加载数据
                LoadData();

                // 显示导入结果
                var resultMessage = string.Format("导入完成！\n成功导入：{0}条\n跳过：{1}条", importedCount, skippedCount);
                if (errorMessages.Any())
                {
                    resultMessage += string.Format("\n\n错误信息：\n{0}", string.Join("\n", errorMessages.Take(10)));
                    if (errorMessages.Count > 10)
                    {
                        resultMessage += string.Format("\n...还有{0}个错误", errorMessages.Count - 10);
                    }
                }

                MessageBox.Show(resultMessage, "导入结果", MessageBoxButton.OK, 
                    errorMessages.Any() ? MessageBoxImage.Warning : MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("导入失败：{0}", ex.Message), "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private List<string> ParseCsvLine(string line)
        {
            var result = new List<string>();
            var current = new StringBuilder();
            bool inQuotes = false;

            for (int i = 0; i < line.Length; i++)
            {
                char c = line[i];
                
                if (c == '"')
                {
                    inQuotes = !inQuotes;
                }
                else if (c == ',' && !inQuotes)
                {
                    result.Add(current.ToString());
                    current.Clear();
                }
                else
                {
                    current.Append(c);
                }
            }
            
            result.Add(current.ToString());
            return result;
        }

        private void ExportShipDataToExcel(string filePath)
        {
            try
            {
                var csvContent = new StringBuilder();
                
                // 添加标题行
                csvContent.AppendLine("母船船号,流用船船号");
                
                // 添加数据行
                foreach (var item in ShipConfigList)
                {
                    csvContent.AppendLine(string.Format("{0},{1}", EscapeCsvValue(item.MotherShipNo), EscapeCsvValue(item.StreamShipNo)));
                }
                
                // 保存CSV文件
                File.WriteAllText(filePath, csvContent.ToString(), Encoding.UTF8);

                // 使用默认程序打开文件
                Process.Start(new ProcessStartInfo
                {
                    FileName = filePath,
                    UseShellExecute = true
                });
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("导出失败：{0}", ex.Message));
            }
        }

        private string EscapeCsvValue(string value)
        {
            if (string.IsNullOrEmpty(value))
                return string.Empty;
                
            // 如果值包含逗号、引号或换行符，需要用引号包围并转义引号
            if (value.Contains(",") || value.Contains("\"") || value.Contains("\n") || value.Contains("\r"))
            {
                return "\"" + value.Replace("\"", "\"\"") + "\"";
            }
            
            return value;
        }

        private bool IsValidShipNo(string shipNo)
        {
            if (string.IsNullOrWhiteSpace(shipNo))
                return false;

            // 检查是否为大写字母+数字的组合
            return System.Text.RegularExpressions.Regex.IsMatch(shipNo, @"^[A-Z]+\d+$");
        }
    }
}
